package com.gitee.wsl.doc.prosemirror.model.content.ext

import com.gitee.wsl.doc.prosemirror.model.content.NodeRange
import com.gitee.wsl.doc.prosemirror.model.node.ext.canCut


// Try to find a target depth to which the content in the given range can be lifted. Will not go
// across [isolating](#model.NodeSpec.isolating) parent nodes.
fun NodeRange.liftTarget(): Int? {
    val range = this
    val parent = range.parent
    val content = parent.content.cutByIndex(range.startIndex, range.endIndex)
    var depth = range.depth
    while (true) {
        val node = range.from.node(depth)
        val index = range.from.index(depth)
        val endIndex = range.to.indexAfter(depth)
        if (depth < range.depth && node.canReplace(index, endIndex, content)) {
            return depth
        }
        if (depth == 0 || node.type.spec.isolating == true || !node.canCut( index, endIndex)) break
        --depth
    }
    return null
}